"""
User Management Views
"""
from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated, IsAdminUser
from django.contrib.auth.models import User
from django.db.models import Count

from .models import UserGroup
from .serializers import UserGroupSerializer, UserWithGroupsSerializer, UserSimpleSerializer


class UserGroupViewSet(viewsets.ModelViewSet):
    """用户组ViewSet"""
    queryset = UserGroup.objects.all()
    serializer_class = UserGroupSerializer
    permission_classes = [IsAuthenticated]
    
    def get_queryset(self):
        """获取查询集"""
        queryset = UserGroup.objects.all()
        
        # 按分类筛选
        category = self.request.query_params.get('category')
        if category:
            queryset = queryset.filter(category=category)
        
        # 搜索
        search = self.request.query_params.get('search')
        if search:
            queryset = queryset.filter(name__icontains=search)
        
        return queryset
    
    @action(detail=True, methods=['post'])
    def add_users(self, request, pk=None):
        """向组中添加用户"""
        group = self.get_object()
        user_ids = request.data.get('user_ids', [])
        
        if not user_ids:
            return Response(
                {'error': '请提供用户ID列表'},
                status=status.HTTP_400_BAD_REQUEST
            )
        
        users = User.objects.filter(id__in=user_ids)
        group.users.add(*users)
        
        return Response({
            'message': f'成功添加 {users.count()} 个用户',
            'user_count': group.user_count
        })
    
    @action(detail=True, methods=['post'])
    def remove_users(self, request, pk=None):
        """从组中移除用户"""
        group = self.get_object()
        user_ids = request.data.get('user_ids', [])
        
        if not user_ids:
            return Response(
                {'error': '请提供用户ID列表'},
                status=status.HTTP_400_BAD_REQUEST
            )
        
        users = User.objects.filter(id__in=user_ids)
        group.users.remove(*users)
        
        return Response({
            'message': f'成功移除 {users.count()} 个用户',
            'user_count': group.user_count
        })
    
    @action(detail=False, methods=['get'])
    def statistics(self, request):
        """获取用户组统计信息"""
        all_groups = UserGroup.objects.all()
        
        stats = {
            'total_groups': all_groups.count(),
            'total_users': User.objects.filter(is_active=True).count(),
            'by_category': {}
        }
        
        for choice in UserGroup.CATEGORY_CHOICES:
            category_code = choice[0]
            category_name = choice[1]
            category_groups = all_groups.filter(category=category_code)
            
            stats['by_category'][category_code] = {
                'name': category_name,
                'group_count': category_groups.count(),
                'user_count': sum(g.user_count for g in category_groups),
                'groups': UserGroupSerializer(category_groups, many=True).data
            }
        
        return Response(stats)


class UserManagementViewSet(viewsets.ReadOnlyModelViewSet):
    """用户管理ViewSet（只读，用于查看和分配组）"""
    queryset = User.objects.all()
    serializer_class = UserWithGroupsSerializer
    permission_classes = [IsAuthenticated]
    
    def get_queryset(self):
        """获取查询集"""
        queryset = User.objects.filter(is_active=True)
        
        # 按组筛选
        group_id = self.request.query_params.get('group_id')
        if group_id:
            queryset = queryset.filter(user_groups__id=group_id)
        
        # 搜索
        search = self.request.query_params.get('search')
        if search:
            queryset = queryset.filter(
                username__icontains=search
            ) | queryset.filter(
                email__icontains=search
            )
        
        return queryset.distinct()
    
    @action(detail=True, methods=['post'])
    def update_groups(self, request, pk=None):
        """更新用户所属的组"""
        user = self.get_object()
        group_ids = request.data.get('group_ids', [])
        
        groups = UserGroup.objects.filter(id__in=group_ids)
        user.user_groups.set(groups)
        
        return Response({
            'message': '用户组更新成功',
            'groups': UserGroupSerializer(user.user_groups.all(), many=True).data
        })
